package service;


import classloader.WebAppClassloader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author yk
 * @version 1.0
 * @date 2021/2/26
 */
public class Bootstrap {

    private int port =8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    private Map<String,HttpServlet> map = new HashMap<String,HttpServlet>();

    public void start() throws Exception {

        //加载解析server.xml
        loadServer();

        //加载web.xml文件
//        loadServlet();

        //创建线程池
        //1	corePoolSize	int	核心线程池大小
        //2	maximumPoolSize	int	最大线程池大小
        //3	keepAliveTime	long	线程最大空闲时间
        //4	unit	TimeUnit	时间单位
        //5	workQueue	BlockingQueue<Runnable>	线程等待队列
        //6	threadFactory	ThreadFactory	线程创建工厂
        //7	handler	RejectedExecutionHandler	拒绝策略
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

         /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket socket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
//        while (true){
//            Socket accept = socket.accept();
//            // 如果接受到8080请求端口，则获取输出流
//            OutputStream outputStream = accept.getOutputStream();
//            String data = "Hello MiniCat!";
//            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length)+data;
//            outputStream.write(responseText.getBytes());
//            // 关闭连接
//            accept.close();
//        }

        /*
          完成Minicat 2.0版本
          需求：封装Request和Response对象，返回html静态资源文件
         */
//        while(true) {
//            Socket accept = socket.accept();
//            InputStream inputStream = accept.getInputStream();
//
//            // 封装Request对象和Response对象
//            Request request = new Request(inputStream);
//            Response response = new Response(accept.getOutputStream());
//
//            response.outputHtml(request.getUrl());
//            accept.close();
//
//        }

        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
//        while ( true ){
//            Socket accept = socket.accept();
//            Request request = new Request(accept.getInputStream());
//            Response response = new Response(accept.getOutputStream());
//
//            if ( map.get( request.getUrl() ) ==null ){
//                response.outputHtml(request.getUrl());
//            }else {
//                map.get(request.getUrl()).service(request,response);
//            }
//            accept.close();
//        }
        /*
          不使用线程池
         */
//        while (true){
//            Socket accept = socket.accept();
//            RequestProcessor requestProcessor = new RequestProcessor(accept, map);
//            requestProcessor.start();
//        }
        System.out.println("============>>>>>> 使用线程池");
        /*
            多线程改造（使用线程池）
        */
        while (true){
            Socket accept = socket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(accept, map);
            threadPoolExecutor.execute(requestProcessor);
        }

    }

    private void loadServer() throws Exception {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();

            Element connectorElement = (Element) rootElement.selectSingleNode("//Connector");
            String port = connectorElement.attributeValue("port");
            setPort(Integer.parseInt(port));

            List<Element> hostElements = rootElement.selectNodes("//Host");
            for (Element hostElement : hostElements) {
//                String hostname = hostElement.attributeValue("name");
                String appBase = hostElement.attributeValue("appBase");
                List<Element> contextElements = hostElement.selectNodes("Context");
                if (contextElements != null) {
                    for (Element contextElement : contextElements) {
                        String contextName = contextElement.attributeValue("name");
                        String path = contextElement.attributeValue("path");

                        File baseFile = new File(appBase+"\\"+path);
                        File[] files = baseFile.listFiles();
                        for (int i = 0; i < files.length; i++) {
                            File web = files[i];
                            if ( web.isDirectory() ){
                                // 解析web.xml
                                loadXml(web,contextName);
                            }
                        }
                }
                }
//                mapper.addHost(host);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadXml(File web,String name) throws ClassNotFoundException, FileNotFoundException, InstantiationException, DocumentException, IllegalAccessException {
        File classPath = new File(web,"/classes");
        URL[] urls = new URL[1];
        try {
            urls[0] = classPath.toURI().toURL();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        // 自定义构造器
        WebAppClassloader webAppClassloader = new WebAppClassloader(urls);
        // 加载web.xml,并解析出Wapper
        File webXml = new File(web,"/web.xml");
        if (webXml.exists()){
            createWapper(name,webAppClassloader,webXml);
        }


    }

    /**
     * 解析xml并对map进行塞值
     *
     * @param webAppClassloader web应用程序类加载器
     * @param webXml            web xml
     */
    private void createWapper(String name,WebAppClassloader webAppClassloader, File webXml) throws FileNotFoundException, ClassNotFoundException, IllegalAccessException, InstantiationException, DocumentException {
        InputStream inputStream = new FileInputStream(webXml);
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> servlet = rootElement.selectNodes("//servlet");
        // 快捷键 itli
        for (int i = 0; i < servlet.size(); i++) {
            Element element =  servlet.get(i);
            // <servlet-name>lagou</servlet-name>
            Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
            String servletName = servletnameElement.getStringValue();
            // <servlet-class>server.LagouServlet</servlet-class>
            Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
            String servletclass = servletclassElement.getStringValue();
            // 根据servlet-name的值找到url-pattern
            Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name = '" + servletName + "']");
            if ( servletMapping != null ){
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                //  /demo1/lagou
                urlPattern = name+urlPattern;
                map.put( urlPattern, (HttpServlet) webAppClassloader.loadClass(servletclass).newInstance());
            }

        }
    }


    /**
     * 加载servlet
     *
     * @throws DocumentException      文件异常
     * @throws ClassNotFoundException 类没有发现异常
     * @throws IllegalAccessException 非法访问异常
     * @throws InstantiationException 实例化异常
     */
    public void loadServlet() throws DocumentException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        InputStream resourceAsStream = Bootstrap.class.getClassLoader().getResourceAsStream("web.xml");
        Document document = new SAXReader().read(resourceAsStream);
        Element rootElement = document.getRootElement();
        List<Element> servlet = rootElement.selectNodes("//servlet");
        // 快捷键 itli
        for (int i = 0; i < servlet.size(); i++) {
            Element element =  servlet.get(i);
            // <servlet-name>lagou</servlet-name>
            Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
            String servletName = servletnameElement.getStringValue();
            // <servlet-class>server.LagouServlet</servlet-class>
            Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
            String servletclass = servletclassElement.getStringValue();
            // 根据servlet-name的值找到url-pattern
            Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name = '" + servletName + "']");
            if ( servletMapping != null ){
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                map.put( urlPattern, (HttpServlet) Class.forName(servletclass).newInstance());
            }

        }
    }

    public static void main(String[] args) {

        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
